<template>
  <div class="request-funds">
    <!--    start form-->
    <div class="filter-content">
      <el-form ref="form" :model="searchObj">
        <div class="params-form params-form-gray">
          <el-form-item label="客户名称">
            <el-input v-model="searchObj.customerName" placeholder="请输入客户名称/小区名称/手机号" />
          </el-form-item>
          <el-form-item label="收款人">
            <el-select-v2
              v-model="searchObj.recipientId"
              filterable
              remote
              :remote-method="query => remoteMethodPartner(query)"
              clearable
              :options="payerOptions"
              :props="{ label: 'payeeName', value: 'payeeId' }"
              placeholder="请输入收款人名称"
            />
          </el-form-item>
          <el-form-item label="创建人">
            <el-select v-model="searchObj.founderId" placeholder="请选择">
              <el-option v-for="(item, index) in founderOptions" :label="item.creatorName" :value="item.creatorId" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div class="filter-button">
        <el-button :icon="Search" type="primary" @click="initTableList">查询</el-button>
        <el-button :icon="RefreshRight" plain type="primary" @click="resetTableList" style="background: #ffffff !important"
          >重置</el-button
        >
      </div>
    </div>
    <!--    end form-->
    <!--    start tab-content-->
    <div class="tab-content">
      <el-tabs v-model="tabActive" @tab-change="initTableList">
        <el-tab-pane v-for="(item, index) in tabList" :label="item" :name="index" />
      </el-tabs>
    </div>
    <!--    end tab-content-->
    <!--    start action-button-->
    <div class="action-button">
      <el-button type="primary" :disabled="!multipleSelection.length" @click="initiatePayment">发起付款</el-button>
      <el-button type="primary" plain @click="exportData" :loading="exportLoading">{{
        exportLoading ? "正在导出" : "按查询条件导出"
      }}</el-button>
    </div>
    <!--    end action-button-->
    <!--     start table-content + pagination -->
    <div class="table-content">
      <div class="table-content__table" v-loading="tableLoading">
        <el-table :data="tableData" style="width: 100%" height="calc(100vh - 500px)" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="customerName" label="客户" min-width="120" />
          <el-table-column prop="communityName" label="小区名称" min-width="200" />
          <el-table-column prop="payeeName" label="收款人" />
          <el-table-column prop="occupationName" label="工种" />
          <el-table-column label="请款金额" min-width="100">
            <template #default="{ row }"> ￥{{ row.requestedAmount }}</template>
          </el-table-column>
          <el-table-column label="已付款金额" min-width="100">
            <template #default="{ row }"> ￥{{ row.paidAmount }}</template>
          </el-table-column>
          <el-table-column label="剩余金额" min-width="100">
            <template #default="{ row }">
              <span class="red-font">￥{{ row.remainingAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="费用说明" min-width="200" show-overflow-tooltip />
          <el-table-column label="状态">
            <template #default="{ row }">
              <span
                class="status-tag"
                :style="{
                  background: statusObj[row.fundApplicationStatus]?.bgColor,
                  color: statusObj[row.fundApplicationStatus]?.color
                }"
                >{{ statusObj[row.fundApplicationStatus]?.text }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="200" />
          <el-table-column prop="fundApplicationNo" label="单据单号" min-width="200" />
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                size="small"
                @click="publicOperate(row, statusObj[row.fundApplicationStatus]?.showButton)"
                v-if="row.fundApplicationStatus != 4"
              >
                {{ statusObj[row.fundApplicationStatus]?.showButton.text }}
              </el-button>

              <el-popover placement="bottom" :width="80" trigger="hover" v-if="row.fundApplicationStatus != 4">
                <template #reference>
                  <el-button type="primary" link size="small" class="expand-button">展开</el-button>
                </template>
                <div class="button-list" v-for="btnItem in statusObj[row.fundApplicationStatus]?.expandButton">
                  <el-button type="primary" link size="small" @click="publicOperate(row, btnItem)">{{ btnItem.text }}</el-button>
                </div>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-model:current-page="pageInfo.current"
        v-model:page-size="pageInfo.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--    end table-content + pagination-->
    <!--    start 详情-->
    <detail v-if="showDetail" v-model="showDetail" :currentApplicationNo="currentApplicationNo"></detail>
    <!--    end 详情-->
    <!--    start 审批记录-->
    <Audit v-model:show="visibleAudit" v-if="visibleAudit" :code="code" />
    <!--    end 审批记录-->
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import { RefreshRight, Search } from "@element-plus/icons-vue";
import detail from "./components/detail";
import { statusObj } from "./config.js";
import {
  requestsFundsList,
  payeeList,
  creatorList,
  requestFundsOperate,
  requestPayment,
  exportRecord
} from "@/apis/requestsFunds";
import Audit from "@/views/audit/index.vue";
import exportExcel from "@/utils/exportExcel";

const route = useRoute();
const router = useRouter();

const { proxy } = getCurrentInstance();

//搜索
const searchObj = ref({
  customerName: "",
  recipientId: "",
  founderId: ""
});
const payerOptions = ref([]);
const founderOptions = ref([]);
const getPayeeList = async value => {
  const { data } = await payeeList({ partnerName: value });
  payerOptions.value = data ?? [];
};
const remoteMethodPartner = value => {
  if (value.trim() == "") {
    payerOptions.value = [];
    return;
  } else {
    getPayeeList(value);
  }
};
const getFounderList = async () => {
  const { data } = await creatorList({ creatorName: "" });
  founderOptions.value = data ?? [];
};
const resetTableList = () => {
  searchObj.value = {
    customerName: "",
    recipientId: "",
    founderId: ""
  };
  initTableList();
};

//tab
const tabStatusObj = {
  0: [0, 1, 2, 3, 4],
  1: [0],
  2: [1],
  3: [3],
  4: [2]
};
const tabActive = ref(0);
const tabList = ["全部", "待审批", "审批中", "未通过", "已审批"];

//分页
const total = ref(0);
const pageInfo = ref({
  current: 1,
  size: 10
});
const handleSizeChange = val => {
  pageInfo.value.size = val;
  getTableList();
};
const handleCurrentChange = val => {
  pageInfo.value.current = val;
  getTableList();
};

//表格
const multipleSelection = ref([]);
const tableLoading = ref(false);
const tableData = ref([]);
const getTableList = async () => {
  tableLoading.value = true;
  let params = {
    keywords: searchObj.value.customerName,
    payeeId: searchObj.value.recipientId,
    fundApplicationStatus: tabStatusObj[tabActive.value],
    createId: searchObj.value.founderId,
    current: pageInfo.value.current,
    size: pageInfo.value.size
  };
  const { data } = await requestsFundsList(params);
  tableData.value = data.list ?? [];
  total.value = data.total ?? 0;
  tableLoading.value = false;
};
const initTableList = () => {
  pageInfo.value.current = 1;
  getTableList();
};
const handleSelectionChange = val => {
  multipleSelection.value = val;
};

//表格操作按钮
const visibleAudit = ref(false);
const showDetail = ref(false);
const currentApplicationNo = ref("");
const code = ref("");
const publicOperate = (row, currentStatusObj) => {
  currentApplicationNo.value = row.fundApplicationNo;
  code.value = row.approvalInstanceId;
  const { text, type } = currentStatusObj;
  if (type === "DETAIL") {
    showDetail.value = true;
  } else if (type === "RECORD") {
    visibleAudit.value = true;
    // code.value = item.processCode;
  } else {
    proxy.$modal
      .confirm(`确定要${text}吗？`)
      .then(async () => {
        await requestFundsOperate({ fundApplicationNo: row.fundApplicationNo, action: type });
        proxy.$modal.msgSuccess("操作成功");
        initTableList();
      })
      .catch(() => {});
  }
};

//发起付款
const initiatePayment = () => {
  const filterData = multipleSelection.value.find(item => item.fundApplicationStatus === 2 && !item.isPaymentRequest);
  if (!filterData) {
    return proxy.$modal.msgWarning("仅已审批状态和未付款可发起付款，请重新选择");
  }
  const fundApplicationNos = multipleSelection.value.map(item => item.fundApplicationNo);
  proxy.$modal
    .confirm("确定要发起付款吗？")
    .then(async () => {
      await requestPayment({ fundApplicationNos: fundApplicationNos });
      proxy.$modal.msgSuccess("操作成功");
      initTableList();
    })
    .catch(() => {});
};

//导出
const exportLoading = ref(false);
const exportData = async () => {
  let params = {
    keywords: searchObj.value.customerName,
    payeeId: searchObj.value.recipientId,
    fundApplicationStatus: tabStatusObj[tabActive.value],
    createId: searchObj.value.founderId,
    current: pageInfo.value.current,
    size: pageInfo.value.size
  };
  exportLoading.value = true;
  const res = await exportRecord(params);
  exportExcel(res, "请款管理");
  exportLoading.value = false;
};

getTableList();
getFounderList();
</script>

<style lang="scss" scoped>
@import "@/assets/styles/index";
@import "@/assets/styles/mixin";

.request-funds {
  @include flex-column;
  height: 100%;
  padding-top: 20px;
  //filter-content
  .filter-content {
    background: #f6f8fa;
    margin: 0 20px 20px 20px;
    .filter-button {
      text-align: right;
      padding: 0 40px 20px 0;
    }
  }

  //params-form
  .params-form {
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;

    .el-form-item {
      margin-right: 20px;

      :deep(.el-input__wrapper),
      :deep(.el-select__wrapper) {
        width: 248px;
      }

      &:last-child {
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  //tab-content
  .tab-content {
    :deep(.el-tabs__nav-scroll) {
      padding-left: 20px;
    }

    :deep(.el-tabs__nav-wrap:after) {
      height: 1px;
      transform: scaleX(1.5);
    }
  }

  //action-button
  .action-button {
    padding: 0 20px;
    margin-bottom: 10px;
  }

  //table-content
  //表格样式
  .table-content {
    margin: 0 20px 20px 20px;
    box-sizing: border-box;
    .expand-button {
      cursor: pointer;
      color: #409eff;
    }

    .status-tag {
      @include blockStyle(56px, 20px, #dcdfe6, 2px);
      border: 1px solid #ffffff;
      display: inline-block;
      @include flexStyle(center, center);
      font-size: 12px;
    }

    :deep(.el-table) {
      border: 1px solid #dcdfe6;

      tr {
        height: 45px;
      }

      tr th {
        background: #f2f6fc;
        font-weight: normal;
        font-size: 14px;
        color: #909399;
      }

      tr td {
        color: #606266;
      }

      tr:nth-of-type(even) td {
        background: #f5f7fa;
      }
    }
  }

  :deep(.el-pagination) {
    margin: 20px;
    justify-content: flex-end;
    background: #fff;
  }
}

.red-font {
  color: #ea0000;
}
</style>
